<template>
  <div class="permission-management">
    <div class="header">
      <h2>权限管理</h2>
      <p class="subtitle">管理系统角色和权限配置</p>
    </div>

    <!-- 视图切换 -->
    <div class="view-tabs">
      <button 
        :class="['tab-btn', { active: activeView === 'roles' }]"
        @click="activeView = 'roles'"
      >
        <i class="fas fa-user-tag"></i>
        角色管理
      </button>
      <button 
        :class="['tab-btn', { active: activeView === 'permissions' }]"
        @click="activeView = 'permissions'"
      >
        <i class="fas fa-key"></i>
        权限管理
      </button>
      <button 
        :class="['tab-btn', { active: activeView === 'assignments' }]"
        @click="activeView = 'assignments'"
      >
        <i class="fas fa-link"></i>
        权限分配
      </button>
    </div>

    <!-- 角色管理 -->
    <div v-if="activeView === 'roles'" class="roles-view">
      <div class="toolbar">
        <div class="search-box">
          <i class="fas fa-search"></i>
          <input 
            v-model="roleSearchQuery" 
            type="text" 
            placeholder="搜索角色名称或描述"
            @input="searchRoles"
          >
        </div>
        <button class="btn btn-primary" @click="showCreateRoleModal">
          <i class="fas fa-plus"></i>
          创建角色
        </button>
      </div>

      <div class="roles-grid">
        <div v-for="role in roles" :key="role.id" class="role-card">
          <div class="role-header">
            <div class="role-info">
              <h3>{{ role.name }}</h3>
              <p>{{ role.description }}</p>
              <div class="role-meta">
                <span class="role-type">{{ getRoleTypeLabel(role.type) }}</span>
                <span class="user-count">{{ role.user_count || 0 }} 用户</span>
              </div>
            </div>
            <div class="role-actions">
              <button 
                class="btn btn-outline btn-sm"
                @click="editRole(role)"
                title="编辑角色"
              >
                <i class="fas fa-edit"></i>
              </button>
              <button 
                class="btn btn-outline btn-sm"
                @click="manageRolePermissions(role)"
                title="管理权限"
              >
                <i class="fas fa-key"></i>
              </button>
              <button 
                v-if="!role.is_system"
                class="btn btn-danger btn-sm"
                @click="deleteRole(role)"
                title="删除角色"
              >
                <i class="fas fa-trash"></i>
              </button>
            </div>
          </div>
          
          <div class="permissions-preview">
            <h4>权限预览</h4>
            <div class="permission-tags">
              <span 
                v-for="permission in role.permissions?.slice(0, 3)" 
                :key="permission.id"
                class="permission-tag"
              >
                {{ permission.name }}
              </span>
              <span 
                v-if="role.permissions?.length > 3"
                class="permission-tag more"
              >
                +{{ role.permissions.length - 3 }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 权限管理 -->
    <div v-if="activeView === 'permissions'" class="permissions-view">
      <div class="toolbar">
        <div class="search-box">
          <i class="fas fa-search"></i>
          <input 
            v-model="permissionSearchQuery" 
            type="text" 
            placeholder="搜索权限名称或描述"
            @input="searchPermissions"
          >
        </div>
        <select v-model="permissionCategoryFilter" @change="loadPermissions">
          <option value="">全部分类</option>
          <option value="user">用户管理</option>
          <option value="course">课程管理</option>
          <option value="exam">考试管理</option>
          <option value="question">题库管理</option>
          <option value="system">系统管理</option>
        </select>
        <button class="btn btn-primary" @click="showCreatePermissionModal">
          <i class="fas fa-plus"></i>
          创建权限
        </button>
      </div>

      <div class="permissions-table">
        <table>
          <thead>
            <tr>
              <th>权限名称</th>
              <th>权限代码</th>
              <th>分类</th>
              <th>描述</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="permission in permissions" :key="permission.id">
              <td>{{ permission.name }}</td>
              <td><code>{{ permission.code }}</code></td>
              <td>
                <span :class="['category-tag', permission.category]">
                  {{ getCategoryLabel(permission.category) }}
                </span>
              </td>
              <td>{{ permission.description }}</td>
              <td>{{ formatDate(permission.created_at) }}</td>
              <td>
                <div class="action-buttons">
                  <button 
                    class="btn btn-outline btn-sm"
                    @click="editPermission(permission)"
                    title="编辑权限"
                  >
                    <i class="fas fa-edit"></i>
                  </button>
                  <button 
                    v-if="!permission.is_system"
                    class="btn btn-danger btn-sm"
                    @click="deletePermission(permission)"
                    title="删除权限"
                  >
                    <i class="fas fa-trash"></i>
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 权限分配 -->
    <div v-if="activeView === 'assignments'" class="assignments-view">
      <div class="assignment-type-tabs">
        <button 
          :class="['tab-btn', { active: assignmentType === 'user' }]"
          @click="assignmentType = 'user'"
        >
          <i class="fas fa-user"></i>
          用户权限
        </button>
        <button 
          :class="['tab-btn', { active: assignmentType === 'role' }]"
          @click="assignmentType = 'role'"
        >
          <i class="fas fa-users"></i>
          角色权限
        </button>
      </div>

      <!-- 用户权限分配 -->
      <div v-if="assignmentType === 'user'" class="user-permissions">
        <div class="toolbar">
          <div class="search-box">
            <i class="fas fa-search"></i>
            <input 
              v-model="userSearchQuery" 
              type="text" 
              placeholder="搜索用户"
              @input="searchUsers"
            >
          </div>
          <select v-model="userTypeFilter" @change="loadUsers">
            <option value="">全部类型</option>
            <option value="teacher">教师</option>
            <option value="student">学生</option>
            <option value="admin">管理员</option>
          </select>
        </div>

        <div class="user-list">
          <div v-for="user in users" :key="user.id" class="user-item">
            <div class="user-info">
              <div class="user-basic">
                <h4>{{ user.name }}</h4>
                <p>{{ user.email }}</p>
                <span :class="['user-type-tag', user.type]">
                  {{ getUserTypeLabel(user.type) }}
                </span>
              </div>
              <div class="user-roles">
                <h5>当前角色</h5>
                <div class="role-tags">
                  <span 
                    v-for="role in user.roles" 
                    :key="role.id"
                    class="role-tag"
                  >
                    {{ role.name }}
                  </span>
                </div>
              </div>
            </div>
            <div class="user-actions">
              <button 
                class="btn btn-primary btn-sm"
                @click="manageUserPermissions(user)"
              >
                <i class="fas fa-cog"></i>
                管理权限
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 角色权限分配 -->
      <div v-if="assignmentType === 'role'" class="role-permissions">
        <div class="role-permission-grid">
          <div v-for="role in roles" :key="role.id" class="role-permission-card">
            <div class="role-header">
              <h3>{{ role.name }}</h3>
              <p>{{ role.description }}</p>
            </div>
            <div class="permission-list">
              <h4>已分配权限 ({{ role.permissions?.length || 0 }})</h4>
              <div class="permission-items">
                <div 
                  v-for="permission in role.permissions" 
                  :key="permission.id"
                  class="permission-item"
                >
                  <span>{{ permission.name }}</span>
                  <button 
                    class="btn btn-danger btn-xs"
                    @click="removePermissionFromRole(role.id, permission.id)"
                  >
                    <i class="fas fa-times"></i>
                  </button>
                </div>
              </div>
              <button 
                class="btn btn-outline btn-sm"
                @click="manageRolePermissions(role)"
              >
                <i class="fas fa-plus"></i>
                添加权限
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建/编辑角色模态框 -->
    <div v-if="showRoleModal" class="modal-overlay" @click="closeModals">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>{{ editingRole ? '编辑角色' : '创建角色' }}</h3>
          <button class="close-btn" @click="closeModals">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveRole">
            <div class="form-group">
              <label>角色名称 *</label>
              <input 
                v-model="roleForm.name" 
                type="text" 
                required
                placeholder="输入角色名称"
              >
            </div>
            <div class="form-group">
              <label>角色描述</label>
              <textarea 
                v-model="roleForm.description" 
                placeholder="输入角色描述"
                rows="3"
              ></textarea>
            </div>
            <div class="form-group">
              <label>角色类型</label>
              <select v-model="roleForm.type" required>
                <option value="">选择角色类型</option>
                <option value="admin">管理员</option>
                <option value="teacher">教师</option>
                <option value="student">学生</option>
                <option value="custom">自定义</option>
              </select>
            </div>
            <div class="form-actions">
              <button type="button" class="btn btn-outline" @click="closeModals">
                取消
              </button>
              <button type="submit" class="btn btn-primary">
                {{ editingRole ? '更新' : '创建' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 创建/编辑权限模态框 -->
    <div v-if="showPermissionModal" class="modal-overlay" @click="closeModals">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>{{ editingPermission ? '编辑权限' : '创建权限' }}</h3>
          <button class="close-btn" @click="closeModals">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="savePermission">
            <div class="form-group">
              <label>权限名称 *</label>
              <input 
                v-model="permissionForm.name" 
                type="text" 
                required
                placeholder="输入权限名称"
              >
            </div>
            <div class="form-group">
              <label>权限代码 *</label>
              <input 
                v-model="permissionForm.code" 
                type="text" 
                required
                placeholder="输入权限代码，如：user.create"
              >
            </div>
            <div class="form-group">
              <label>权限分类</label>
              <select v-model="permissionForm.category" required>
                <option value="">选择分类</option>
                <option value="user">用户管理</option>
                <option value="course">课程管理</option>
                <option value="exam">考试管理</option>
                <option value="question">题库管理</option>
                <option value="system">系统管理</option>
              </select>
            </div>
            <div class="form-group">
              <label>权限描述</label>
              <textarea 
                v-model="permissionForm.description" 
                placeholder="输入权限描述"
                rows="3"
              ></textarea>
            </div>
            <div class="form-actions">
              <button type="button" class="btn btn-outline" @click="closeModals">
                取消
              </button>
              <button type="submit" class="btn btn-primary">
                {{ editingPermission ? '更新' : '创建' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 权限分配模态框 -->
    <div v-if="showPermissionAssignModal" class="modal-overlay" @click="closeModals">
      <div class="modal large" @click.stop>
        <div class="modal-header">
          <h3>管理 {{ currentTarget?.name }} 的权限</h3>
          <button class="close-btn" @click="closeModals">&times;</button>
        </div>
        <div class="modal-body">
          <div class="permission-assignment">
            <div class="available-permissions">
              <h4>可分配权限</h4>
              <div class="search-box">
                <i class="fas fa-search"></i>
                <input 
                  v-model="availablePermissionsSearch" 
                  type="text" 
                  placeholder="搜索权限"
                >
              </div>
              <div class="permission-list">
                <div 
                  v-for="permission in filteredAvailablePermissions" 
                  :key="permission.id"
                  class="permission-item clickable"
                  @click="assignPermission(permission)"
                >
                  <div class="permission-info">
                    <div class="permission-name">{{ permission.name }}</div>
                    <div class="permission-code">{{ permission.code }}</div>
                  </div>
                  <button class="btn btn-primary btn-sm">
                    <i class="fas fa-plus"></i>
                  </button>
                </div>
              </div>
            </div>
            
            <div class="assigned-permissions">
              <h4>已分配权限</h4>
              <div class="permission-list">
                <div 
                  v-for="permission in currentTargetPermissions" 
                  :key="permission.id"
                  class="permission-item assigned"
                >
                  <div class="permission-info">
                    <div class="permission-name">{{ permission.name }}</div>
                    <div class="permission-code">{{ permission.code }}</div>
                  </div>
                  <button 
                    class="btn btn-danger btn-sm"
                    @click="removePermission(permission)"
                  >
                    <i class="fas fa-minus"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>
          <div class="form-actions">
            <button type="button" class="btn btn-outline" @click="closeModals">
              关闭
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { 
  getRoles,
  createRole,
  updateRole,
  deleteRole as deleteRoleAPI,
  getPermissions,
  createPermission,
  updatePermission,
  deletePermission as deletePermissionAPI,
  getUsers,
  assignPermissionToRole,
  removePermissionFromRole as removePermissionFromRoleAPI,
  assignPermissionToUser,
  removePermissionFromUser
} from '@/api/rbac'

export default {
  name: 'PermissionManagement',
  setup() {
    const activeView = ref('roles')
    const assignmentType = ref('user')
    
    // 角色相关
    const roles = ref([])
    const roleSearchQuery = ref('')
    
    // 权限相关
    const permissions = ref([])
    const permissionSearchQuery = ref('')
    const permissionCategoryFilter = ref('')
    
    // 用户相关
    const users = ref([])
    const userSearchQuery = ref('')
    const userTypeFilter = ref('')
    
    // 模态框状态
    const showRoleModal = ref(false)
    const showPermissionModal = ref(false)
    const showPermissionAssignModal = ref(false)
    
    // 编辑状态
    const editingRole = ref(null)
    const editingPermission = ref(null)
    const currentTarget = ref(null)
    const currentTargetType = ref('') // 'role' or 'user'
    
    // 表单数据
    const roleForm = reactive({
      name: '',
      description: '',
      type: ''
    })
    
    const permissionForm = reactive({
      name: '',
      code: '',
      category: '',
      description: ''
    })
    
    // 权限分配相关
    const availablePermissions = ref([])
    const currentTargetPermissions = ref([])
    const availablePermissionsSearch = ref('')
    
    // 计算属性
    const filteredAvailablePermissions = computed(() => {
      if (!availablePermissionsSearch.value) return availablePermissions.value
      const query = availablePermissionsSearch.value.toLowerCase()
      return availablePermissions.value.filter(permission => 
        permission.name.toLowerCase().includes(query) ||
        permission.code.toLowerCase().includes(query)
      )
    })
    
    // 方法
    const loadRoles = async () => {
      try {
        const params = {
          search: roleSearchQuery.value,
          pageSize: 100
        }
        const response = await getRoles(params)
        roles.value = response.data.data || []
      } catch (error) {
        console.error('加载角色列表失败:', error)
      }
    }
    
    const loadPermissions = async () => {
      try {
        const params = {
          search: permissionSearchQuery.value,
          category: permissionCategoryFilter.value,
          pageSize: 100
        }
        const response = await getPermissions(params)
        permissions.value = response.data.data || []
      } catch (error) {
        console.error('加载权限列表失败:', error)
      }
    }
    
    const loadUsers = async () => {
      try {
        const params = {
          search: userSearchQuery.value,
          type: userTypeFilter.value,
          pageSize: 100
        }
        const response = await getUsers(params)
        users.value = response.data.data || []
      } catch (error) {
        console.error('加载用户列表失败:', error)
      }
    }
    
    const searchRoles = () => {
      loadRoles()
    }
    
    const searchPermissions = () => {
      loadPermissions()
    }
    
    const searchUsers = () => {
      loadUsers()
    }
    
    const getRoleTypeLabel = (type) => {
      const labels = {
        admin: '管理员',
        teacher: '教师',
        student: '学生',
        custom: '自定义'
      }
      return labels[type] || type
    }
    
    const getCategoryLabel = (category) => {
      const labels = {
        user: '用户管理',
        course: '课程管理',
        exam: '考试管理',
        question: '题库管理',
        system: '系统管理'
      }
      return labels[category] || category
    }
    
    const getUserTypeLabel = (type) => {
      const labels = {
        teacher: '教师',
        student: '学生',
        admin: '管理员'
      }
      return labels[type] || type
    }
    
    const formatDate = (dateString) => {
      return new Date(dateString).toLocaleDateString('zh-CN')
    }
    
    const showCreateRoleModal = () => {
      editingRole.value = null
      Object.assign(roleForm, {
        name: '',
        description: '',
        type: ''
      })
      showRoleModal.value = true
    }
    
    const showCreatePermissionModal = () => {
      editingPermission.value = null
      Object.assign(permissionForm, {
        name: '',
        code: '',
        category: '',
        description: ''
      })
      showPermissionModal.value = true
    }
    
    const editRole = (role) => {
      editingRole.value = role
      Object.assign(roleForm, {
        name: role.name,
        description: role.description,
        type: role.type
      })
      showRoleModal.value = true
    }
    
    const editPermission = (permission) => {
      editingPermission.value = permission
      Object.assign(permissionForm, {
        name: permission.name,
        code: permission.code,
        category: permission.category,
        description: permission.description
      })
      showPermissionModal.value = true
    }
    
    const saveRole = async () => {
      try {
        if (editingRole.value) {
          await updateRole(editingRole.value.id, roleForm)
        } else {
          await createRole(roleForm)
        }
        closeModals()
        loadRoles()
      } catch (error) {
        console.error('保存角色失败:', error)
      }
    }
    
    const savePermission = async () => {
      try {
        if (editingPermission.value) {
          await updatePermission(editingPermission.value.id, permissionForm)
        } else {
          await createPermission(permissionForm)
        }
        closeModals()
        loadPermissions()
      } catch (error) {
        console.error('保存权限失败:', error)
      }
    }
    
    const deleteRole = async (role) => {
      if (confirm(`确定要删除角色 "${role.name}" 吗？`)) {
        try {
          await deleteRoleAPI(role.id)
          loadRoles()
        } catch (error) {
          console.error('删除角色失败:', error)
        }
      }
    }
    
    const deletePermission = async (permission) => {
      if (confirm(`确定要删除权限 "${permission.name}" 吗？`)) {
        try {
          await deletePermissionAPI(permission.id)
          loadPermissions()
        } catch (error) {
          console.error('删除权限失败:', error)
        }
      }
    }
    
    const manageRolePermissions = async (role) => {
      currentTarget.value = role
      currentTargetType.value = 'role'
      
      try {
        // 加载角色已有权限
        currentTargetPermissions.value = role.permissions || []
        
        // 加载所有权限
        const allPermissionsResponse = await getPermissions({ pageSize: 1000 })
        const assignedPermissionIds = currentTargetPermissions.value.map(p => p.id)
        availablePermissions.value = allPermissionsResponse.data.data.filter(
          permission => !assignedPermissionIds.includes(permission.id)
        )
        
        showPermissionAssignModal.value = true
      } catch (error) {
        console.error('加载权限信息失败:', error)
      }
    }
    
    const manageUserPermissions = async (user) => {
      currentTarget.value = user
      currentTargetType.value = 'user'
      
      try {
        // 加载用户已有权限
        currentTargetPermissions.value = user.permissions || []
        
        // 加载所有权限
        const allPermissionsResponse = await getPermissions({ pageSize: 1000 })
        const assignedPermissionIds = currentTargetPermissions.value.map(p => p.id)
        availablePermissions.value = allPermissionsResponse.data.data.filter(
          permission => !assignedPermissionIds.includes(permission.id)
        )
        
        showPermissionAssignModal.value = true
      } catch (error) {
        console.error('加载权限信息失败:', error)
      }
    }
    
    const assignPermission = async (permission) => {
      try {
        if (currentTargetType.value === 'role') {
          await assignPermissionToRole(currentTarget.value.id, permission.id)
        } else {
          await assignPermissionToUser(currentTarget.value.id, permission.id)
        }
        
        // 更新本地状态
        currentTargetPermissions.value.push(permission)
        availablePermissions.value = availablePermissions.value.filter(p => p.id !== permission.id)
        
        // 刷新主列表
        if (currentTargetType.value === 'role') {
          loadRoles()
        } else {
          loadUsers()
        }
      } catch (error) {
        console.error('分配权限失败:', error)
      }
    }
    
    const removePermission = async (permission) => {
      try {
        if (currentTargetType.value === 'role') {
          await removePermissionFromRoleAPI(currentTarget.value.id, permission.id)
        } else {
          await removePermissionFromUser(currentTarget.value.id, permission.id)
        }
        
        // 更新本地状态
        currentTargetPermissions.value = currentTargetPermissions.value.filter(p => p.id !== permission.id)
        availablePermissions.value.push(permission)
        
        // 刷新主列表
        if (currentTargetType.value === 'role') {
          loadRoles()
        } else {
          loadUsers()
        }
      } catch (error) {
        console.error('移除权限失败:', error)
      }
    }
    
    const removePermissionFromRole = async (roleId, permissionId) => {
      try {
        await removePermissionFromRoleAPI(roleId, permissionId)
        loadRoles()
      } catch (error) {
        console.error('移除角色权限失败:', error)
      }
    }
    
    const closeModals = () => {
      showRoleModal.value = false
      showPermissionModal.value = false
      showPermissionAssignModal.value = false
      editingRole.value = null
      editingPermission.value = null
      currentTarget.value = null
      currentTargetType.value = ''
      availablePermissionsSearch.value = ''
    }
    
    onMounted(() => {
      loadRoles()
      loadPermissions()
      loadUsers()
    })
    
    return {
      activeView,
      assignmentType,
      roles,
      permissions,
      users,
      roleSearchQuery,
      permissionSearchQuery,
      permissionCategoryFilter,
      userSearchQuery,
      userTypeFilter,
      showRoleModal,
      showPermissionModal,
      showPermissionAssignModal,
      editingRole,
      editingPermission,
      currentTarget,
      roleForm,
      permissionForm,
      availablePermissions,
      currentTargetPermissions,
      availablePermissionsSearch,
      filteredAvailablePermissions,
      loadRoles,
      loadPermissions,
      loadUsers,
      searchRoles,
      searchPermissions,
      searchUsers,
      getRoleTypeLabel,
      getCategoryLabel,
      getUserTypeLabel,
      formatDate,
      showCreateRoleModal,
      showCreatePermissionModal,
      editRole,
      editPermission,
      saveRole,
      savePermission,
      deleteRole,
      deletePermission,
      manageRolePermissions,
      manageUserPermissions,
      assignPermission,
      removePermission,
      removePermissionFromRole,
      closeModals
    }
  }
}
</script>

<style scoped>
.permission-management {
  padding: 0;
}

.header {
  margin-bottom: 24px;
}

.header h2 {
  margin: 0 0 8px 0;
  color: #1f2937;
}

.subtitle {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.view-tabs,
.assignment-type-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 24px;
  background: #f3f4f6;
  padding: 4px;
  border-radius: 8px;
  width: fit-content;
}

.tab-btn {
  padding: 8px 16px;
  border: none;
  background: transparent;
  color: #6b7280;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.tab-btn:hover {
  background: #e5e7eb;
}

.tab-btn.active {
  background: #3b82f6;
  color: white;
}

.toolbar {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  align-items: center;
}

.search-box {
  position: relative;
  flex: 1;
  max-width: 400px;
}

.search-box i {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #6b7280;
}

.search-box input {
  width: 100%;
  padding: 8px 12px 8px 36px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.toolbar select {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-sm {
  padding: 6px 12px;
  font-size: 12px;
}

.btn-xs {
  padding: 4px 8px;
  font-size: 11px;
}

.btn-primary {
  background: #3b82f6;
  color: white;
}

.btn-danger {
  background: #ef4444;
  color: white;
}

.btn-outline {
  background: transparent;
  color: #6b7280;
  border: 1px solid #d1d5db;
}

.btn:hover {
  opacity: 0.8;
}

/* 角色管理样式 */
.roles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.role-card {
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 20px;
  transition: box-shadow 0.2s;
}

.role-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.role-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.role-info h3 {
  margin: 0 0 4px 0;
  color: #1f2937;
  font-size: 18px;
}

.role-info p {
  margin: 0 0 8px 0;
  color: #6b7280;
  font-size: 14px;
}

.role-meta {
  display: flex;
  gap: 12px;
  align-items: center;
}

.role-type {
  padding: 4px 8px;
  background: #dbeafe;
  color: #1e40af;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.user-count {
  color: #6b7280;
  font-size: 12px;
}

.role-actions {
  display: flex;
  gap: 8px;
}

.permissions-preview h4 {
  margin: 0 0 8px 0;
  color: #374151;
  font-size: 14px;
  font-weight: 600;
}

.permission-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.permission-tag {
  padding: 4px 8px;
  background: #f3f4f6;
  color: #374151;
  border-radius: 4px;
  font-size: 12px;
}

.permission-tag.more {
  background: #e5e7eb;
  color: #6b7280;
}

/* 权限管理样式 */
.permissions-table {
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
}

.permissions-table table {
  width: 100%;
  border-collapse: collapse;
}

.permissions-table th,
.permissions-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #e5e7eb;
}

.permissions-table th {
  background: #f9fafb;
  font-weight: 600;
  color: #374151;
}

.permissions-table code {
  background: #f3f4f6;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  color: #1f2937;
}

.category-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.category-tag.user {
  background: #dbeafe;
  color: #1e40af;
}

.category-tag.course {
  background: #d1fae5;
  color: #065f46;
}

.category-tag.exam {
  background: #fef3c7;
  color: #92400e;
}

.category-tag.question {
  background: #e0e7ff;
  color: #3730a3;
}

.category-tag.system {
  background: #fce7f3;
  color: #be185d;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

/* 权限分配样式 */
.user-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.user-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
}

.user-basic h4 {
  margin: 0 0 4px 0;
  color: #1f2937;
}

.user-basic p {
  margin: 0 0 8px 0;
  color: #6b7280;
  font-size: 14px;
}

.user-type-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.user-type-tag.teacher {
  background: #dbeafe;
  color: #1e40af;
}

.user-type-tag.student {
  background: #d1fae5;
  color: #065f46;
}

.user-type-tag.admin {
  background: #fef3c7;
  color: #92400e;
}

.user-roles h5 {
  margin: 8px 0 4px 0;
  color: #374151;
  font-size: 12px;
}

.role-tags {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.role-tag {
  padding: 2px 6px;
  background: #f3f4f6;
  color: #374151;
  border-radius: 4px;
  font-size: 11px;
}

.role-permission-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.role-permission-card {
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 20px;
}

.role-permission-card .role-header h3 {
  margin: 0 0 4px 0;
  color: #1f2937;
}

.role-permission-card .role-header p {
  margin: 0 0 16px 0;
  color: #6b7280;
  font-size: 14px;
}

.permission-list h4 {
  margin: 0 0 12px 0;
  color: #374151;
  font-size: 14px;
  font-weight: 600;
}

.permission-items {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 12px;
  max-height: 200px;
  overflow-y: auto;
}

.permission-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f9fafb;
  border-radius: 6px;
  border: 1px solid #e5e7eb;
}

.permission-item.clickable {
  cursor: pointer;
  transition: background 0.2s;
}

.permission-item.clickable:hover {
  background: #f3f4f6;
}

.permission-item.assigned {
  background: #f0f9ff;
}

.permission-info {
  flex: 1;
}

.permission-name {
  font-weight: 500;
  color: #1f2937;
  font-size: 14px;
}

.permission-code {
  color: #6b7280;
  font-size: 12px;
  font-family: monospace;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal.large {
  max-width: 900px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
}

.modal-header h3 {
  margin: 0;
  color: #1f2937;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #6b7280;
}

.modal-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 4px;
  color: #374151;
  font-weight: 500;
  font-size: 14px;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.form-group textarea {
  resize: vertical;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.permission-assignment {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 24px;
}

.available-permissions,
.assigned-permissions {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
}

.available-permissions h4,
.assigned-permissions h4 {
  margin: 0 0 12px 0;
  color: #1f2937;
  font-size: 16px;
}

.available-permissions .permission-list,
.assigned-permissions .permission-list {
  max-height: 400px;
  overflow-y: auto;
}

@media (max-width: 768px) {
  .roles-grid,
  .role-permission-grid {
    grid-template-columns: 1fr;
  }
  
  .permission-assignment {
    grid-template-columns: 1fr;
  }
  
  .role-header,
  .user-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>